<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error="error"
    error-text="加载失败，请点击重试"
    @load="onLoad"
    :immediate-check="false"
  >
    <!-- <van-cell v-for="(item, i) in list" :key="i" :title="item.content" /> -->
    <comment-item
      v-for="(item, i) in list"
      :key="i"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
    <!-- <comment-item></comment-item> -->
  </van-list>
</template>

<script>
import { getComment } from '@/api/comments.js';
import CommentItem from '@/components/CommentItem.vue';

export default {
  name: 'CommentList',
  props: {
    source: { type: [Number, Object, String], required: true },
    list: {
      type: Array,
      default: function () {
        return [];
      },
    },
    type: {
      type: String,
      // 自定义 prop 数据验证
      validator(value) {
        return ['a', 'c'].includes(value);
      },
      default: 'a',
    },
  },
  components: {
    CommentItem,
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null,
      limit: 10,
      error: false,
      total_count: 0,
    };
  },
  created() {
    // 手动初始onload的话，它不会自动开始初始的loading
    // 所以我们要手动的开启初始loading
    this.loading = true;
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getComment({
          type: this.type,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit,
        });
        this.list.push(...data.data.results);
        this.$emit('onload-success', data.data);
        this.total_count = data.data.total_count;
        // 加载状态结束
        this.loading = false;
        // 数据全部加载完成
        if (data.data.results.length) {
          this.offset = data.data.last_id;
        } else {
          this.finished = true;
        }
      } catch (err) {
        this.error = true;
        this.loading = false;
      }
    },
  },
};
</script>
<style lang="less" scoped></style>
